package cn.cdzdjd.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import cn.cdzdjd.constant.BrowserConstant;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.ZuiYouService;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ZuiYouServiceImpl implements ZuiYouService {

	@Override
	public VideoInfoVO getVideoInfo(String locationUrl) {
		try {
			Document doc = Jsoup.connect(locationUrl).ignoreContentType(true)
					.userAgent(BrowserConstant.USER_AGENT_MOBILE).header("Accept", BrowserConstant.ACCEPT)
					.referrer(locationUrl).get();
			Element body = doc.body();
			Element sharePost = body.selectFirst("div[class=SharePostCard]");
			Element titleEle = sharePost.getElementsByTag("h1").first();
			String title = titleEle.text();
			Elements videoTag = sharePost.getElementsByTag("video");
			// 如果为空，说明未找到video标签，说明是图文
			if (videoTag.isEmpty()) {
				Element ouerBox = sharePost.selectFirst("div[class=ResponsiveList__inner]");
				Elements imgsElement = ouerBox.getElementsByTag("img");
				List<String> posterList = new ArrayList<>();
				for (int i = 0; i < imgsElement.size(); i++) {
					String poster = imgsElement.get(i).attr("src");
					int index = StringUtils.lastOrdinalIndexOf(poster, "/", 2);
					String posterUrl = poster.substring(0, index);
					posterList.add(UrlUtil.setHttps(posterUrl));
				}
				return new VideoInfoVO(null, posterList, title, null);
			} else {
				Element video = videoTag.first();
				String videoUrl = video.attr("src");
				List<String> videoList = new ArrayList<>();
				videoList.add(UrlUtil.setHttps(videoUrl));
				String poster = video.attr("poster");
				List<String> posterList = new ArrayList<>();
				String posterUrl = poster.split("\\?")[0];
				posterList.add(UrlUtil.setHttps(posterUrl));
				return new VideoInfoVO(videoList, posterList, title, null);
			}
		} catch (IOException e) {
			e.printStackTrace();
			log.error("jsoup访问异常");
			throw new RenException("访问异常");
		}
	}
}
